package com.czkt.config;

import com.alibaba.fastjson.JSON;
import com.czkt.util.JWTUtils;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

@Component
public class CustomAuthenticationSuccessHandler implements AuthenticationSuccessHandler {

    @Override
    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {
        User user = (User) authentication.getPrincipal();

        String token = JWTUtils.createToken(user);

        Map<String ,Object > reslutMap = new HashMap<>();
        reslutMap.put("code","200");
        reslutMap.put("token",token);

        response.getWriter().print(JSON.toJSON(reslutMap));
    }
}
